package cn.crm.util;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Component;

import cn.crm.entity.Permission;
import cn.crm.entity.User;
import cn.crm.mapper.PermissionMapper;

@Component
public class PermissionUtils {
	//@component （把普通pojo实例化到spring容器中，相当于配置文件中的<bean id="" class=""/>）
	
	private static PermissionMapper permissionMapper;
	
	
	public static boolean checkPermission(String resource) {
		User user = (User)UserContext.session.getAttribute(UserContext.USER_IN_SESSION);
		Permission permission = permissionMapper.selectByresource(resource);
		//就是如果index页面判断的权限没有在permission表中就直接return true即可不需要继续判断
		if (permission == null) {
			return true;
		}
		int userId = user.getId();
		
		List<Permission> permissions = permissionMapper.selectByuserId(userId);
		boolean haspermission = false;
		for (Permission permission2 : permissions) {
			if (permission2.getResource().equals(resource)) {
				haspermission = true;
			}
		}
		return haspermission;
	}
	
    // 因为字段为static,不能直接注入,所以注入到setter方法上
	@Autowired(required = true)
    public void setPermissionMapper(PermissionMapper permissionMapper) {
        PermissionUtils.permissionMapper = permissionMapper;
    }

}
